package com.aivin.lint_lib_java.detector;

import com.aivin.lint_lib_java.JavaLog;
import com.android.tools.lint.client.api.UElementHandler;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.android.tools.lint.detector.api.TextFormat;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.uast.UCallExpression;
import org.jetbrains.uast.UElement;
import org.jetbrains.uast.UReferenceExpression;
import org.jetbrains.uast.UastUtils;
import org.jetbrains.uast.util.UastExpressionUtils;

import java.util.Collections;
import java.util.List;


/**
 * 线程创建规范规则
 */
public class AVThreadDetector extends Detector implements Detector.UastScanner {
    public static final Issue ISSUE = Issue.create(
            "Aivin_ThreadIssue",
            "线程使用不规范...",
            "请使用线程池",
            Category.CORRECTNESS,
            9,
            Severity.ERROR,
            new Implementation(AVThreadDetector.class, Scope.JAVA_FILE_SCOPE)
    );

    @Override
    public List<Class<? extends UElement>> getApplicableUastTypes() {
        return Collections.singletonList(UCallExpression.class);
    }

    @Override
    public UElementHandler createUastHandler(@NotNull JavaContext context) {
        return new UElementHandler() {
            @Override
            public void visitCallExpression(@NotNull UCallExpression node) {

                if (!UastExpressionUtils.isConstructorCall(node)) {
                    return;
                }

                UReferenceExpression classRef = node.getClassReference();
                if(classRef ==null){
                    return;
                }


                String className = UastUtils.getQualifiedName(classRef);
                if ("java.lang.Thread".equals(className) && context.getProject().isAndroidProject()) {
                    context.report(
                            ISSUE, node,
                            context.getLocation(node),
                            ISSUE.getBriefDescription(TextFormat.TEXT)   );
                    JavaLog.showLog("检测到线程使用不规范");
                }


            }
        };
    }
}
